import Vue from 'vue'
import { filterEmpty } from '../../utils/vnode'

function getWatch (keys = []) {
  const watch = {}
  keys.forEach(k => {
    watch[k] = function (value) {
      this._proxyVm._data[k] = value
    }
  })
  return watch
}

const ConfigProvider = {
  name: 'ConfigProvider',
  props: {
    prefixCls: String,
    csp: Object
  },
  provide () {
    const _self = this
    this._proxyVm = new Vue({
      data () {
        return {
          ..._self.$props,
          getPrefixCls: _self.getPrefixCls
        }
      }
    })
    return {
      configProvider: this._proxyVm._data
    }
  },
  watch: {
    ...getWatch(['prefixCls', 'csp'])
  },
  methods: {
    getPrefixCls (suffixCls, customizePrefixCls) {
      const { prefixCls = 'v' } = this.$props
      if (customizePrefixCls) return customizePrefixCls
      return suffixCls ? `${prefixCls}-${suffixCls}` : prefixCls
    }
  },
  render () {
    return this.$slots.default ? filterEmpty(this.$slots.default)[0] : null
  }
}

export const ConfigConsumerProps = {
  getPrefixCls: (suffixCls, customizePrefixCls) => {
    if (customizePrefixCls) return customizePrefixCls
    return `v-${suffixCls}`
  }
}

export default ConfigProvider
